<?php


namespace App\Controller;

use App\Model\User;
use Hyperf\Contract\OnCloseInterface;
use Hyperf\Contract\OnMessageInterface;
use Hyperf\Contract\OnOpenInterface;
use Hyperf\Utils\ApplicationContext;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

/**
 * Class WsController
 * @package App\Controller
 */
class WsController implements OnMessageInterface, OnOpenInterface, OnCloseInterface
{
    private $redis;

    public function __construct(){
        $container = ApplicationContext::getContainer();
        if(!$this->redis) {
            $this->redis = $container->get(\Hyperf\Redis\Redis::class);
        }
    }
    public function onMessage($server, Frame $frame): void
    {
        $data = $frame->data;
        $data = json_decode($data,true);
        $user_mobile = $data['user_mobile'] ?? '';
        $key = "user:{$user_mobile}";
        if(!$this->redis->hGet($key,'fd')){
            $server->push($frame->fd, '该用户不在线');
        }

        var_dump($data);
        var_dump($this->redis->hGet($key,'fd'));
        $message = $data['message'] ?? $frame->data;
        $server->push($this->redis->hGet($key,'fd'), $message);
    }

    public function onClose($server, int $fd, int $reactorId): void
    {
        var_dump('closed');
    }

    public function onOpen($server, Request $request): void
    {
        $user_id = $request->get['user_id'];
        $online_key = "USER:ONLINE:SET"; // 把用户加入在线列表中
        $info = User::query()->where('user_id',$user_id)->first();
        if(!$info){
            $server->push($request->fd, '用户未注册，禁止链接');
            $server->disconnect($request->fd);
        }

        $server->push($request->fd, 'Opened');

        if($info && !$this->redis->sIsMember($online_key,$user_id)) {
            $this->redis->sAdd($online_key, $user_id);
        }

        $online_user_key = "USER_ONLINE_{$user_id}";
        if($info && !$this->redis->hGet($online_user_key,'user_id')) {
            $info = $info->toArray();
            foreach ($info as $k => $v){
                $this->redis->hSet($online_user_key, $k,$v);
            }
        }
    }
}